package com.atguigu.eduorder.service.impl;

import com.atguigu.commonutils.OrderVo.OrderCourse;
import com.atguigu.commonutils.OrderVo.OrderMember;
import com.atguigu.eduorder.Client.EduClient;
import com.atguigu.eduorder.Client.UcenterClient;
import com.atguigu.eduorder.utils.OrderNoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.Odd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.eduorder.mapper.TOrderMapper;
import com.atguigu.eduorder.entity.TOrder;
import com.atguigu.eduorder.service.TOrderService;

/**
 * @author cyt
 * @create 2020-06-02 16:03
 */

@Slf4j
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    EduClient eduClient;

    @Autowired
    UcenterClient ucenterClient;

    /**
     * 创建订单 id
     * @param courseId
     * @param memberIdByJwtToken
     * @return
     */
    @Override
    public String saveOrder(String courseId, String memberIdByJwtToken) {
        // 获得课程信息
        OrderCourse course = eduClient.getOrderCourseById(courseId);
        log.info(course.toString());
        // 获得用户信息
        OrderMember member = ucenterClient.getOrderMember(memberIdByJwtToken);
        log.info(member.toString());
        TOrder order = new TOrder();
        /// 生产 id

        order.setOrderNo(OrderNoUtil.getOrderNo());

        order.setCourseCover(course.getCover());

        order.setCourseId(courseId);


        order.setMemberId(memberIdByJwtToken);
        order.setCourseTitle(course.getTitle());
        order.setTeacherName(course.getTeacherName());
        order.setTotalFee(course.getPrice());
        order.setNickname(member.getNickname());
        order.setMobile(member.getMobile());


        /**
         *  支付状态、方式
         */
        order.setStatus((byte) 0);
        order.setPayType((byte) 1);
        baseMapper.insert(order);
        return order.getOrderNo();
    }

    /**
     * 根据用户的id 以及 课程的 id 查询订单信息
     * @param memberId
     * @param courseId
     * @return
     */
    @Override
    public int isBuy(String memberId, String courseId) {

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberId).eq("course_id", courseId).eq("status", 1);

        return baseMapper.selectCount(wrapper);
    }
}
